package com.xm.servlet;


import com.xm.biz.CartBiz;
import com.xm.biz.GoodsBiz;
import com.xm.biz.impl.CartBizImpl;
import com.xm.biz.impl.GoodsBizImpl;
import com.xm.po.Cart;
import com.xm.po.Goods;
import com.xm.po.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xie'lin'feng
 * @date 2020-08-14-9:48
 * @description 购物车处理器
 */
@WebServlet("/car")
public class BuyCarServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        GoodsBiz goodsBiz = new GoodsBizImpl();
        CartBiz cartBiz = new CartBizImpl();
        //获取用户
        HttpSession session = req.getSession();
        Users user = (Users) session.getAttribute("user");
        if (user==null){
            //如果未登录就跳转登录页面
            resp.sendRedirect("login.jsp");
        }else {
            //获取商品id
            Integer id = Integer.valueOf(req.getParameter("id"));
            Integer count = Integer.valueOf(req.getParameter("count"));
            if (id!=null&&count!=null){
                Cart cartById = cartBiz.getCartById(id, user.getUserId());
                //判断用户购物车是否有过一样的商品
                if (cartById!=null){
                    //存在就数量加1
                    cartById.setGoodsCnt(cartById.getGoodsCnt()+count);
                    cartBiz.updateCart(cartById);
                }else {
                    Cart cart = new Cart(null,user.getUserId(),1,id,count);
                    cartBiz.add(cart);
                }
            }
            //获取用户的购物车信息
            List<Cart> cartList = cartBiz.getAll(user.getUserId());
            //获取所有商品信息
            List<Goods> goodsList = goodsBiz.getAll();
            //获取购物车选中的数量
            List<Cart> cartByIdChecked = cartBiz.getCartByIdChecked(user.getUserId());
            //将获取的数据放入会话
            session.setAttribute("sum",cartByIdChecked);
            session.setAttribute("cartList",cartList);
            session.setAttribute("goodsList",goodsList);
            //跳转网页
            resp.sendRedirect("shopcart.jsp");
        }
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
